package pagerouter

import (
	"fmt"
	"net/http"
	"text/template"
	"time"

	"gitee.com/chenrh/ios-local/AppDdistribute/libs"
)

func AppInstall(w http.ResponseWriter, req *http.Request) {

	vars := req.URL.Query()
	appids := vars["appid"]
	vers := vars["ver"]

	if len(appids) == 0 || len(vers) == 0 {
		w.Write([]byte("非法路径"))
		return
	}

	bundleid := appids[0]
	versionName := vers[0]
	helper := libs.NewAppInstallHelper(bundleid, versionName)
	app, err := helper.ParseIPA()
	if err != nil {
		w.Write([]byte(err.Error()))
		return
	}

	viewdata := map[string]interface{}{}
	viewdata["APP"] = app
	viewdata["rnd"] = time.Now().Unix()

	host, _ := libs.NewHostInfo()

	// 生成应用相关的文件
	// 1）生成图标文件，在下载时可以看
	// appFolder := fmt.Sprintf("./static/%s/%s", app.BundleId, app.Version)
	// createFolder(appFolder)

	// iconpath := filepath.Join(appFolder, "icon.png")
	// saveAppIcon(iconpath, app.Icon)

	// 2）iOS生成对应的 plist 文件
	// plistDestPath := filepath.Join(appFolder, "info.plist")
	// libs.NewPlist(host, app, plistDestPath)

	plistDestPath, err := helper.GetPListPath()
	if err != nil {
		w.Write([]byte(err.Error()))
		return
	}

	iconpath, err := helper.GetAppIcon()

	if err == nil {
		iconpath = fmt.Sprintf("/%s", iconpath)
	}

	plistPath := host.SSLSite + plistDestPath
	// apkPath := host.Site + "/static/oa.apk"

	plistPath = "itms-services://?action=download-manifest&url=" + plistPath
	// itemhref :=`itms-services://?action=download-manifest&url=https://192.168.1.76:5433/static/ios.plist`

	viewdata["png_url"] = iconpath
	viewdata["ios_url"] = plistPath
	// viewdata["apk_url"] = apkPath
	// 辅助生成一个 plist
	// libs.NewPlistPublish(host, app)

	t, _ := template.ParseFiles("./views/index-install.html")
	t.Execute(w, viewdata)
}

// func errorToByteArray(err error) []byte {
// 	str := err.Error()
// 	return []byte(str)
// }
